module BatchedSqlFu
  module ActiveRecord
    class StatementInvalid < StandardError; end
    
    module ClassMethods
      def insert_by_batch(flush_every = 100)
        connection.reset_batch_sql_collection!
        alias_insert_sql_to_batched_version!
        begin
          yield
          connection.batch_sql_collection.flush_now!
        rescue Exception => e
          raise e
        ensure
          return_insert_sql_to_normal_version!
        end
      end
      
      protected
        def alias_insert_sql_to_batched_version!
          class << connection
            alias :normal_insert_sql :insert_sql
            def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) #:nodoc:
              batch_sql_collection << sql
            end
          end
        end
        
        def return_insert_sql_to_normal_version!
          class << connection
            alias :insert_sql :normal_insert_sql
          end
        end
    end

    def self.included(ar)
      ar.extend ClassMethods
    end
  end
end